<template>
  <div class="lang-international-set gray-box top-redius border-bottom-gray">
    <div class="title">
      {{ $t('sysManagement.internationalConfig') }}
    </div>
    <el-form
      ref="dataForm"
      label-width="180px"
      class="set-form"
      label-position="left"
    >
      <div class="config-til">
        <el-row>
          <!-- 语言名称 -->
          <el-col :span="4">
            {{ $t('sysManagement.languageName') }}
          </el-col>
          <!-- 语言代码 -->
          <el-col
            :span="4"
            :offset="1"
          >
            {{ $t('sysManagement.languageCode') }}
          </el-col>
          <!-- 语言编号 -->
          <el-col
            :span="4"
            :offset="1"
          >
            {{ $t('sysManagement.languageNumber') }}
          </el-col>
          <!-- 默认语言 -->
          <el-col
            :span="2"
            :offset="1"
          >
            {{ $t('sysManagement.defaultLanguage') }}
          </el-col>
          <!-- 是否隐藏 -->
          <el-col
            :span="2"
            :offset="1"
          >
            {{ $t('sysManagement.whetherHide') }}
          </el-col>
          <el-col
            :span="3"
            :offset="1"
          >
            {{ $t('remindPop.operation') }}
          </el-col>
        </el-row>
      </div>
      <div
        v-for="(item,index) in langItemList"
        :key="index"
      >
        <el-row>
          <!-- 语言名称 -->
          <el-col :span="4">
            <el-form-item
              label=""
              label-width="0"
            >
              <el-input
                v-model.trim="item.name"
                :placeholder="$t('sysManagement.languageName')"
                maxlength="30"
              />
              <div
                v-show="submitStatus&&!item.name"
                class="el-form-item__error tips-con"
              >
                {{ $t('sysManagement.languageNameNotNull') }}
              </div>
            </el-form-item>
          </el-col>
          <!-- 语言代码 -->
          <el-col
            :span="4"
            :offset="1"
          >
            <el-form-item
              label=""
              label-width="0"
            >
              <el-input
                v-model.trim="item.language"
                :placeholder="$t('sysManagement.languageCode')"
                maxlength="20"
                @input="(v)=>(item.language=v.replace(/[^A-Za-z_-]/g,''))"
              />
              <div
                v-show="!item.language&&submitStatus"
                class="el-form-item__error tips-con"
              >
                {{ $t('sysManagement.languageCodeNotNull') }}
              </div>
              <div
                v-show="item.language&&!!item.isFormalError"
                class="el-form-item__error tips-con"
              >
                {{ $t('sysManagement.formatErrorNotContainChinese') }}
              </div>
            </el-form-item>
          </el-col>
          <!-- 语言编号 -->
          <el-col
            :span="4"
            :offset="1"
          >
            <el-form-item
              label=""
              label-width="0"
            >
              <el-input
                v-model.trim="item.lang"
                type="number"
                :min="0"
                :placeholder="$t('sysManagement.languageNumber')"
                @change="langChange(index)"
              />
              <div
                v-show="item.lang === '' && submitStatus"
                class="el-form-item__error tips-con"
              >
                {{ $t('sysManagement.languageNumberNotNull') }}
              </div>
            </el-form-item>
          </el-col>
          <!-- 默认语言 -->
          <el-col
            :span="2"
            :offset="1"
          >
            <el-form-item
              label=""
              label-width="0"
            >
              <el-switch
                v-model="item.master"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                :disabled="item.master === 1"
                @change="(c)=>masterChange(c,index)"
              />
            </el-form-item>
          </el-col>
          <!-- 是否隐藏 -->
          <el-col
            :span="2"
            :offset="1"
          >
            <el-form-item
              label=""
              label-width="0"
            >
              <el-switch
                v-model="item.hide"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                :disabled="masterLangInfo.lang === item.lang"
                @change="(c)=>hideChange(c,item)"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="3"
            :offset="1"
          >
            <el-form-item
              label=""
              label-width="0"
            >
              <span
                class="default-btn text-btn"
                @click="delLang(item,index)"
              >{{ $t('user.deleteBtn') }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div
        class="default-btn primary-btn"
        @click="addLang"
      >
        {{ $t('sysManagement.add') }}
      </div>
      <div
        class="default-btn primary-btn"
        @click="dataFormSubmit()"
      >
        {{ $t('sysManagement.save') }}
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const dataForm = ref(null)
const masterLangInfo = reactive({
  name: '',
  lang: '',
  language: ''
})

// lang:语言编号 master:主语言
const langItemList = ref([
  { name: '中文', lang: 0, master: 1, language: 'zh', hide: 0 }
])
const submitStatus = ref(false)

onMounted(() => {
  init()
})
const langStore = useLangStore()
const init = () => {
  nextTick(() => {
    http({
      url: http.adornUrl('/sys/pconfig/info/' + 'INTERNATIONALIZATION_CONFIG'),
      method: 'get'
    }).then(({ data }) => {
      if (data) {
        const info = JSON.parse(data)
        langStore.updateLang(info)
        masterLangInfo.name = info.name
        masterLangInfo.lang = info.lang
        masterLangInfo.language = info.language
        langItemList.value = info.langItemList.map(m => {
          const reg = /[^A-Za-z_-]/g
          m.isFormalError = reg.test(m.language)
          return m
        })
      }
    })
  })
}

// 语言编码限制
const langChange = (inx) => {
  let val = langItemList.value[inx].lang || 0
  val = Math.trunc(Math.abs(val))
  if (val > 1000) {
    val = 1000
  }
  langItemList.value[inx].lang = val
}

// 添加语言
const addLang = () => {
  langItemList.value.push({ name: '', lang: '', master: 0, language: '', hide: 0 })
}

// 删除语言
const delLang = (item, index) => {
  if (item.master) {
    ElMessage({
      message: $t('sysManagement.mainLanguageNotDelete'),
      type: 'error',
      duration: 1000
    })
    return
  }
  langItemList.value.splice(index, 1)
}

// 设置主语言
// eslint-disable-next-line no-unused-vars
const masterChange = (c, inx) => {
  // 主语言不可隐藏
  langItemList.value[inx].hide = 0
  // 主语言信息
  masterLangInfo.name = langItemList.value[inx].name
  masterLangInfo.lang = langItemList.value[inx].lang
  masterLangInfo.language = langItemList.value[inx].language
  langItemList.value.forEach((item, index) => {
    if (index !== inx && item.master === 1) {
      item.master = 0
      item.hide = 0
    }
  })
}

// 隐藏限制
const hideChange = (c, curItem) => {
  if (c === 1 && curItem.master === 1) {
    curItem.hide = 0
  }
}
// 验证是否可提交
const isSubmit = () => {
  const langArr = []
  for (const item of langItemList.value) {
    if (item.name === '' || item.lang === '' || item.language === '') {
      return false
    }
    langArr.push(item.lang)
  }
  const reLangArr = [...new Set(langArr)]
  if (reLangArr.length !== langArr.length) {
    ElMessage({
      message: $t('sysManagement.duplicateLanguage'),
      type: 'error',
      duration: 1500
    })
    return false
  }
  for (const item of langItemList.value) {
    if (item.isFormalError) {
      return false
    }
  }
  return true
}

// 表单提交
const dataFormSubmit = () => {
  submitStatus.value = true
  if (!isSubmit()) {
    return
  }
  for (const langItem of langItemList.value) {
    if (langItem.master) {
      masterLangInfo.name = langItem.name
      masterLangInfo.lang = langItem.lang
      masterLangInfo.language = langItem.language
      break
    }
  }

  const paramsData = {
    ...masterLangInfo,
    langItemList: langItemList.value
  }
  http({
    url: http.adornUrl('/sys/pconfig/save'),
    method: 'post',
    data: http.adornData({
      paramKey: 'INTERNATIONALIZATION_CONFIG',
      paramValue: JSON.stringify(paramsData),
      remark: $t('sysManagement.internationalConfig')
    })
  }).then(() => {
    init()
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500
    })
  })
}

</script>
<style scoped>
.config-til {
  margin-bottom: 12px;
}

.tips-con {
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
</style>
